package persistence

import (
	"errors"
	"example.com/m/v2/internal/domain/account_aggregate/entity"
	"gorm.io/gorm"
	"time"
)

type SubordinateAccountPo struct {
	gorm.Model

	MainAccountId uint `gorm:"column:main_account_id;not null;index:bind_ma_appid,priority:1"`
	AppId         uint `gorm:"column:app_id;not null;index:bind_ma_appid,priority:2"`

	Nickname string `gorm:"column:nick_name;type:varchar(32)"`
	Avatar   string `gorm:"column:avatar;type:varchar(128)"`

	LastLoginTime time.Time `gorm:"column:last_login_time;type:datetime;not null"`
}

func (po *SubordinateAccountPo) TableName() string {
	return "sub_account"
}

func (po *SubordinateAccountPo) ToEntity() (*entity.SubAccountEntity, error) {
	if po == nil {
		return nil, errors.New("nil main account po object")
	}
	return &entity.SubAccountEntity{
		Id:            po.ID,
		AppId:         po.AppId,
		MainAccountId: po.MainAccountId,
		Nickname:      po.Nickname,
		Avatar:        po.Avatar,
		CreateTime:    po.CreatedAt,
		LastLoginTime: po.LastLoginTime,
	}, nil
}

func (po *SubordinateAccountPo) FromEntity(entity *entity.SubAccountEntity) error {
	po.ID = entity.Id
	po.AppId = entity.AppId
	po.MainAccountId = entity.MainAccountId
	po.Nickname = entity.Nickname
	po.Avatar = entity.Avatar
	po.LastLoginTime = entity.LastLoginTime
	return nil
}
